package com.baidu.process.config;

import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;


@Configuration
public class OkHttpConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(OkHttpConfiguration.class);

    @Value("${okhttp.config.connect:1000}") //连接超时
    private String connectTime;
    @Value("${okhttp.config.read:1000}")    //读取超时
    private String readTime;
    @Value("${okhttp.config.write:1000}")
    private String writeTime;
    @Value("${connection.pool.maxIdle:1000}")
    private String maxIdleConnections;
    @Value("${connection.pool.keepAlive:1000}")
    private String keepAliveDuration;
    /**
    * 描  述: 通过@Bean给配置类注入一个OKHttp的客户端对象，加入了ssl的信任代理
    * 参  数:
    * 返回值: okhttp3.OkHttpClient
    * 创建时间: 2020/8/26
    */
    @Bean
    public OkHttpClient okHttpClient() {

//        return new OkHttpClient.Builder()
//                .sslSocketFactory(sslSocketFactory(), x509TrustManager())
//                .retryOnConnectionFailure(false)  //true重试  false不开启重试
//                .connectionPool(pool())
//                .connectTimeout(Integer.parseInt(connectTime), TimeUnit.SECONDS)
//                .readTimeout(Integer.parseInt(readTime), TimeUnit.SECONDS)
//                .writeTimeout(Integer.parseInt(writeTime),TimeUnit.SECONDS)
//                .build();
        return new OkHttpClient().newBuilder()
                .build();
    }

    /**
    * 描  述: 生成509TrustManager
    * 参  数:
    * 返回值: javax.net.ssl.X509TrustManager
    * 创建时间: 2020/8/26
    */
    @Bean
    public X509TrustManager x509TrustManager() {
        return new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            }
            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            }
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };
    }

    /**
    * 描  述:生成ssl工厂类
    * 参  数:
    * 返回值: javax.net.ssl.SSLSocketFactory
    * 创建时间: 2020/8/26
    */
    @Bean
    public SSLSocketFactory sslSocketFactory() {
        try {
            //信任任何链接
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[]{x509TrustManager()}, new SecureRandom());
            return sslContext.getSocketFactory();
        } catch (NoSuchAlgorithmException e) {
        	logger.error(e.toString());
        } catch (KeyManagementException e) {
        	logger.error(e.toString());
        }
        return null;
    }

    /**
    * 描  述: 建立连接池初始化
    * 参  数:
    * 返回值: okhttp3.ConnectionPool
    * 创建时间: 2020/8/26
    */
    @Bean
    public ConnectionPool pool() {
        return new ConnectionPool(Integer.parseInt(maxIdleConnections), Integer.parseInt(keepAliveDuration), TimeUnit.MINUTES);
    }
}
